﻿using System;
using System.Web;
using System.IO;
using System.Text;
using System.Web.SessionState;
using PreguntaAlExperto.RulesLayer.Services;
using System.Configuration;
using PreguntaAlExperto.RulesLayer.Entities;
using PreguntaAlExperto.TransporterObjectsFramework;
using Microsoft.Security.Application;
using Common;

namespace PreguntaAlExperto
{
    public class GenericHandler
        : IHttpHandler, IRequiresSessionState
    {
        public GenericHandler()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            String filePath = Path.GetFileNameWithoutExtension(context.Request.FilePath);
            StringWriter _stringWriter = new StringWriter();
            string _articleHandlerPath = "~/showArticle.aspx";
            string _articleTXTFileName = Path.Combine(ConfigurationManager.AppSettings["FileRepository"], filePath + ".txt");
            string _articleASPXFileName = filePath + ".aspx";
            
            StringBuilder _textMerger = new StringBuilder();

            try
            {
                ArticlesService _service = new ArticlesService();
                Article _article = _service.getArticleByPath(_articleASPXFileName);
                BaseList<Comments> _comments = _service.getComments(_article.Article_ID);
                _service.updateVisit(_articleASPXFileName);
                context.Server.Execute(_articleHandlerPath, _stringWriter);
                _textMerger.Append(_stringWriter.ToString());

                context.Application.Lock();
                StreamReader _stringReader = new StreamReader(_articleTXTFileName, System.Text.Encoding.UTF7);
                string _articleContent = _stringReader.ReadToEnd();
                _stringReader.Close();
                string articleContent = HtmlSanitizer.HtmlSanitizer.Process(_articleContent);
                context.Application.UnLock();

                _textMerger.Replace("<articletitle>", _article.Title);
                _textMerger.Replace("<contextreplace></contextreplace>", articleContent);
                _textMerger.Replace("<TotalShine>", (_article.TotalPoints / _article.TotalVotes).ToString());
                _textMerger.Replace("<TotalVotes>", _article.TotalVotes.ToString());
                _textMerger.Replace("<RequestedURL>", _article.Path);

                _textMerger.Replace("<autorinformation>",
                    String.Format("<a href='{0}/rss.aspx?q=publicador&p={1}'><img src='{0}/images/rss.gif' alt='Atículos publicados por {2}' border='0' align='absmiddle'/></a> Autor: {2} - ",
                        HtmlHelpers.BaseUrl, 
                        _article.Publisher_ID,
                        _article.PublisherEntity.Name)
                + _article.Publish_Date.ToShortDateString()
                + "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tags: <i>" + string.Join(", ", _article.AllCategories) + "</i>");

                BaseList<Article> _relatedArticles = _service.getRelatedArticles(_article.Group_ID);
                if (_relatedArticles.Count > 0)
                {
                    StringBuilder _relatedBuilder = new StringBuilder();
                    _relatedBuilder.Append("<table width=\"100%\" border=\"0\"><tr><td class=\"headerRelatedArticles\" align=\"left\">Artículos relacionados</td>");
                    _relatedBuilder.Append("</tr>");
                    foreach (Article _related in _relatedArticles)
                    {
                        _relatedBuilder.Append("<tr><td align=\"left\" class=\"SmallFontSize\" style=\"\"><div class=\"containerClass\"><a href=\"http://www.preguntaalexperto.net/articles/" + _related.Path + "\">" + _related.Title + "</a></div></td></tr>");
                    }
                    _relatedBuilder.Append("</table><br />");
                    _textMerger.Replace("<relatedContent></relatedContent>", _relatedBuilder.ToString());
                }

                StringBuilder _commentsString = new StringBuilder();
                foreach (Comments _comment in _comments)
                {
                    _commentsString.Append(_comment.Comment.Replace("\n","<br>"));
                    if (_comment.IsMember)
                    {
                        _commentsString.Append("<br><div style=\"font-size:11px; color:#FF6600; padding-bottom:4px; padding-top: 4px; margin-bottom:8px; border-bottom: dashed 1px #CCCCCC\"><img src=\"/images/miniBrainOn.jpg\" alt=\"Moderador\"> Publicado por: ");
                    }
                    else
                    { 
                        _commentsString.Append("<br><div style=\"font-size:11px; color:#FF6600; padding-bottom:4px; padding-top: 4px; margin-bottom:8px; border-bottom: dashed 1px #CCCCCC\">Publicado por: ");
                    }
                    _commentsString.Append(_comment.Name);
                    _commentsString.Append("</div>");
                }
                _textMerger.Replace("<comments>", _commentsString.ToString());

            }
            catch (ArticleNotFoundException e)
            {
                context.Response.Redirect("~/documents/ArticleNotFound.aspx");
            }
            context.Response.Write(_textMerger.ToString());
            context.Application.Lock();
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}